from twisted.spread import pb
from twisted.internet import reactor

from option import Option

class UserAvatar(pb.Avatar):
	def __init__(self, name, mind, priv = 0):
		self.name = name
		self.mind = mind
		self.priv = priv
		Option().chat.announceEnter(self)
		Option().users.append(self)
		Option().log.info('New user %s logged in' % name)

	def connectionLost(self):
		Option().users.remove(self)
		Option().chat.announceLeave(self)
		Option().log.info('User %s has disconnected' % self.name)

	def getInfo(self):
		return (self.name, self.priv)

	# Chat functions

	def perspective_chat(self, msg):
		Option().chat.send(self.name, msg.replace('\n', ' '))

	def send(self, msg):
		self.mind.callRemote('send',msg)
		
	def notify(self, param1, param2):
		self.mind.callRemote('notify', param1, param2)
				
	def perspective_getUsers(self):
		return [(x.name, x.priv) for x in Option().users]

	# Competition functions

	def perspective_getEvents(self):
		return Option().events

	def perspective_getEventsInfo(self):
		return [x.view_getInfo(self) for x in Option().events]


class Realm:
	def requestAvatar(self, avatarId, mind, *interfaces):
		avatar = UserAvatar(avatarId, mind)
		return None, avatar, lambda a=avatar: a.connectionLost()


